package org.yanfengying.user.interceptor;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.yanfengying.user.domain.Logininfo;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.util.Objects;
@Component
public class LoginInterceptor implements HandlerInterceptor {

    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //1 拿到前端穿回来的token
        String token = request.getHeader("token");
        if(StringUtils.isNoneBlank(token)){
            //2 根据token查询相关信息->不存在就拦截->存在就放行
            Logininfo logininfo = (Logininfo)redisTemplate.opsForValue().get(token);
            if(Objects.nonNull(logininfo)){//不为空->存在
                return true;
            }
        }
            //不为空
            response.setCharacterEncoding("utf-8");//解决乱码问题
            response.setContentType("application/json; charset=UTF-8");

            PrintWriter writer = response.getWriter();
            writer.write("{\"success\":false,\"message\":\"noLogin\"}");
            writer.close();
            return false;
    }
}
